import path from 'path';
import fs from 'fs';
import { defineConfig } from 'rollup';
import terser from '@rollup/plugin-terser';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import replace from '@rollup/plugin-replace';

const meta = JSON.parse(fs.readFileSync(path.resolve('./package.json')).toString());

const MODULE_NAME = 'CloudWeb';

const BANNER =
	'/*!\n' +
	` * ${meta.name} v${meta.version}\n` +
	` * ${new Date()}\n` +
	` * (c) 2024-${new Date().getFullYear()} 3dnest\n` +
	' */';

const moduleList = [
	{
		output: path.resolve(`dist/${MODULE_NAME}.js`),
		format: 'umd',
		name: MODULE_NAME,
		isUglify: false
	},
	{
		output: path.resolve(`dist/${MODULE_NAME}.esm.js`),
		format: 'es',
		name: MODULE_NAME,
		isUglify: false
	},
	{
		output: path.resolve(`dist/${MODULE_NAME}.min.js`),
		format: 'umd',
		name: MODULE_NAME,
		isUglify: true
	},
	{
		output: path.resolve(`dist/${MODULE_NAME}.esm.min.js`),
		format: 'es',
		name: MODULE_NAME,
		isUglify: true
	},
];

export default moduleList.map(config => {
	const pluginList = [
		nodeResolve({
			browser: true,
			preferBuiltins: false
		}),
		commonjs(),
		json(),
		replace({
			'__env__': process.env.NODE_ENV,
			'__buildDate__': new Date(),
			preventAssignment: true
		}),
	];

	if (config.isUglify) {
		pluginList.push(terser());
	}

	return defineConfig({
		input: path.resolve('./src/index.js'),
		output: {
			file: config.output,
			format: config.format,
			name: config.name,
			banner: BANNER
		},
		plugins: pluginList
	});
});
